package compiler.dot;

import java.io.PrintStream;
import java.util.HashMap;

public class GraphHelper {
	private int count;
	private PrintStream out;
	private HashMap<Object, String> nodeMap;
	
	public GraphHelper(PrintStream _out, String graphName) {
		count = -1;
		out = _out;
		nodeMap = new HashMap<Object,String>();
		
		out.println("digraph "+graphName+" {\nnode [shape=record];");
	}
	
	public void startSubgraph(String graphName) {
		
	}

	public void close() {
		out.println("}");
	}
	
	public boolean addNode(Object obj, String label) {
		if (nodeMap.containsKey(obj)) {
			return false;
		}
		
		String node = "n" + getCount();
		nodeMap.put(obj, node);
		
		String nodeFormat = node + " [label=\"" + label + "\"];";
		out.println(nodeFormat);
		
		return true;
	}
	
	public void addEdge(Object parent, Object child) {
		String p = nodeMap.get(parent);
		String c = nodeMap.get(child);
		
		if (p != null && c != null) {
			out.println(p+"->"+c+";");
		}
	}
	
	public boolean contains(Object obj) {
		return nodeMap.containsKey(obj);
	}
	
	private int getCount() {
		count++;
		return count;
	}
}
